package dal

import (
	"github.com/gin-gonic/gin"
	"honghu_be/dal/po"
)

func CreateArticle(c *gin.Context, articlePo *po.Article) error {
	sql := GetDB().Model(po.Article{})
	return sql.Create(articlePo).Error
}

func DeleteArticle(c *gin.Context, articleId int) error {
	sql := GetDB().Model(po.Article{})
	return sql.Delete(po.Article{}, articleId).Error
}

type GetArticlesRequest struct {
	ArticleId int `json:"article_id"`
	Limit     int `json:"limit"`
	Offset    int `json:"offset"`
}

func GetArticles(c *gin.Context, req *GetArticlesRequest) ([]*po.Article, error) {
	var pos []*po.Article
	sql := GetDB().Model(po.Article{})
	if req.ArticleId != 0 {
		sql = sql.Where("id = ?", req.ArticleId)
	}
	if req.Limit > 0 {
		sql = sql.Limit(req.Limit)
	} else {
		sql = sql.Limit(10)
	}
	if req.Offset > 0 {
		sql = sql.Offset(req.Offset)
	}
	sql = sql.Find(&pos)
	return pos, sql.Error
}

func UpdateArticle(c *gin.Context, articleId int, articlePo *po.Article) error {
	sql := GetDB().Model(po.Article{})
	sql = sql.Where("id = ?", articleId)
	err := sql.Updates(articlePo).Error
	if err != nil {
		return err
	}
	sql.First(articlePo)
	return nil
}
